<template>
  <div>
    <APopover
      ref="propverRef"
      v-model:popup-visible="showPopover"
      trigger="click"
      scroll-to-close
      :scroll-to-close-distance="100"
    >
      <ABadge :count="loadTaskNum" :max-count="99" :offset="[-12, 3]">
        <li class="nav-btn-box">
          <icon-subscribe class="nav-btn" />
          <span class="erp-font-size-12 erp-mt-3">便签</span>
        </li>
      </ABadge>
      <template #content>
        <div class="erp-mb-8">
          <AButton type="outline" :loading="addBtnLoad" @click="openEdit('新增便签')">新增</AButton>
        </div>
        <ATabs
          v-model:active-key="activeTab"
          type="card-gutter"
          destroy-on-hide
          lazy-load
          @change="tabChange"
        >
          <!-- <ATabPane key="" title="全部">
            <AScrollbar>
              <div v-for="(item, index) in noteList" :key="index" class="note-item">
                <div>
                  <div>
                    <ACheckbox
                      v-model:model-value="item.isFinish"
                      @change="(value: any) => finishTask(value, item)"
                    ></ACheckbox>
                  </div>
                  <div></div>
                </div>
                <div class="note-content" @click="openEdit('编辑便签', item)">
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskName }}</div>
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskEndDate }}</div>
                </div>
                <div
                  style="
                    margin-right: 4px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <icon-close style="cursor: pointer" @click="deleteTask(item)" />
                  </div>
                  <div :class="priorityClass[item.taskPriority]">
                    {{ priorityText[item.taskPriority] }}
                  </div>
                </div>
              </div>
            </AScrollbar>
          </ATabPane> -->
          <ATabPane :key="0" title="进行中">
            <AEmpty v-if="isEmpty(noteList)"></AEmpty>
            <AScrollbar v-else style="max-height: 60vh; overflow: auto; padding: 0px 10px">
              <div v-for="(item, index) in noteList" :key="index" class="note-item">
                <div>
                  <div>
                    <ACheckbox
                      v-model:model-value="item.isFinish"
                      @change="(value: any) => finishTask(value, item)"
                    ></ACheckbox>
                  </div>
                  <div></div>
                </div>
                <div class="note-content" @click="openEdit('编辑便签', item)">
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskName }}</div>
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskEndDate }}</div>
                </div>
                <div
                  style="
                    margin-right: 4px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <icon-close style="cursor: pointer" @click="deleteTask(item)" />
                  </div>
                  <div :class="priorityClass[item.taskPriority]">
                    {{ priorityText[item.taskPriority] }}
                  </div>
                </div>
              </div>
            </AScrollbar>
          </ATabPane>
          <ATabPane :key="1" title="已完成">
            <AEmpty v-if="isEmpty(noteList)"></AEmpty>
            <AScrollbar v-else style="max-height: 60vh; overflow: auto; padding: 0px 10px">
              <div v-for="(item, index) in noteList" :key="index" class="note-item">
                <div>
                  <div>
                    <ACheckbox
                      v-model:model-value="item.isFinish"
                      @change="(value: any) => finishTask(value, item)"
                    ></ACheckbox>
                  </div>
                  <div></div>
                </div>
                <div class="note-content" @click="openEdit('编辑便签', item)">
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskName }}</div>
                  <div :class="{ red: taskPostpone(item) }">{{ item.taskEndDate }}</div>
                </div>
                <div
                  style="
                    margin-right: 4px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                  "
                >
                  <div>
                    <icon-close style="cursor: pointer" @click="deleteTask(item)" />
                  </div>
                  <div :class="priorityClass[item.taskPriority]">
                    {{ priorityText[item.taskPriority] }}
                  </div>
                </div>
              </div>
            </AScrollbar>
          </ATabPane>
        </ATabs>
      </template>
    </APopover>

    <AModal
      v-model:visible="editModal"
      :title="modalTitle"
      :mask-closable="false"
      @close="modalEvent('close')"
      @ok="modalEvent('ok')"
      @open="modalEvent('open')"
      @cancel="modalEvent('cancel')"
    >
      <AForm ref="formRef" :model="form" auto-label-width layout="vertical">
        <ARow :gutter="10">
          <ACol :span="12">
            <AFormItem
              field="taskName"
              label="名称"
              :rules="[{ required: true, message: '请输入名称' }]"
              :validate-trigger="['change', 'input', 'blur']"
            >
              <AInput v-model="form.taskName" placeholder="请输入名称"></AInput>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="taskStatus" label="状态">
              <ASelect v-model="form.taskStatus" allow-clear placeholder="状态">
                <AOption label="进行中" :value="0"></AOption>
                <AOption label="已完成" :value="1"></AOption>
              </ASelect>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="taskPriority" label="优先级">
              <ASelect v-model="form.taskPriority" allow-clear placeholder="优先级">
                <AOption label="高" :value="0"></AOption>
                <AOption label="中" :value="1"></AOption>
                <AOption label="低" :value="2"></AOption>
              </ASelect>
            </AFormItem>
          </ACol>
          <ACol :span="12">
            <AFormItem field="taskEndDate" label="截止时间">
              <ADatePicker v-model="form.taskEndDate" placeholder="截止时间" class="w100" />
            </AFormItem>
          </ACol>
          <ACol>
            <AFormItem field="taskDesc" label="内容">
              <ATextarea v-model="form.taskDesc" placeholder="请输入内容"></ATextarea>
            </AFormItem>
          </ACol>
        </ARow>
      </AForm>
    </AModal>
  </div>
</template>

<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue'
import {
  delNotes,
  editNotes,
  getNotesDetail,
  getNotesPageList,
  getTaskCount,
  NotesResItem
} from '@renderer/api/globalModule'
import { useMenuState } from '@renderer/store'
import dayjs from 'dayjs'
import { isEmpty } from 'lodash-es'

const noteList = ref<NotesResItem[]>([])
const activeTab = ref<number>(0)
const editModal = ref(false)
const form = ref<NotesResItem>({
  taskId: '',
  taskName: '',
  taskDesc: '',
  taskStatus: 0,
  taskPriority: 0,
  taskEndDate: ''
})
const formRef = ref()
const modalTitle = ref('')
const menuParam = useMenuState()
const noteItem = ref<NotesResItem>({
  taskName: '',
  taskDesc: '',
  taskStatus: 0,
  taskPriority: 0,
  taskEndDate: ''
})
const showPopover = ref(false)
const propverRef = ref()
const priorityClass = ['red', 'yellow', 'gray']
const priorityText = ['高', '中', '低']
const loadTaskNum = ref(0)
const addBtnLoad = ref(false)

const getNoteList = () => {
  getNotesPageList({ taskStatus: activeTab.value }).then((res) => {
    noteList.value = res.data.list.map((item) => {
      item.isFinish = item.taskStatus != 1 ? false : true
      return item
    })
  })
}
const getTaskLoadNum = () => {
  getTaskCount({ taskStatus: 0 }).then((res) => {
    loadTaskNum.value = res.data
  })
}

onMounted(() => {
  getNoteList()
  getTaskLoadNum()
})

const openEdit = (title: string, noteInfo?: NotesResItem) => {
  addBtnLoad.value = true
  modalTitle.value = title
  editModal.value = true
  if (noteInfo) {
    noteItem.value = noteInfo
  }
  addBtnLoad.value = false
}

const getDetail = () => {
  getNotesDetail({ taskId: noteItem.value.taskId! }).then((res) => {
    form.value = res.data
  })
}

// 延期报警
const taskPostpone = (noteInfo: NotesResItem) => {
  if (dayjs().isAfter(dayjs(noteInfo.taskEndDate))) {
    return true
  } else {
    return false
  }
}

// 弹窗事件
const modalEvent = (type: string) => {
  switch (type) {
    case 'ok':
      formRef.value.validate((errors) => {
        if (!errors) {
          // 新增
          if (modalTitle.value.includes('新增')) {
            form.value.taskId = undefined
          }
          editNotes(form.value).then(() => {
            Message.success(modalTitle.value.includes('新增') ? '新增成功' : '修改成功')
            modalEvent('cancel')
            getNoteList()
            getTaskLoadNum()
          })
        }
      })
      break
    case 'close':
      menuParam.switchEditStatus(false)
      formRef.value.resetFields()
      editModal.value = false
      showPopover.value = true
      form.value = {
        taskId: '',
        taskName: '',
        taskDesc: '',
        taskStatus: 0,
        taskPriority: 0,
        taskEndDate: ''
      }
      break
    case 'open':
      menuParam.switchEditStatus(true)
      if (modalTitle.value === '编辑便签') {
        getDetail()
      }
      break
    case 'cancel':
      formRef.value.resetFields()
      menuParam.switchEditStatus(false)
      form.value = {
        taskId: '',
        taskName: '',
        taskDesc: '',
        taskStatus: 0,
        taskPriority: 0,
        taskEndDate: ''
      }
      editModal.value = false
      showPopover.value = true
      break
    default:
      break
  }
}

const deleteTask = (noteInfo: NotesResItem) => {
  Modal.warning({
    title: '警告',
    content: '删除后不可恢复，是否继续删除？',
    okText: '确认',
    cancelText: '取消',
    simple: false,
    hideCancel: false,
    maskClosable: false,
    closable: false,
    width: 'auto',
    onOk: () => {
      delNotes({ taskId: noteInfo.taskId! })
        .then(() => {
          Message.success('删除成功')
        })
        .finally(() => {
          showPopover.value = true
        })
    },
    onCancel: () => {
      showPopover.value = true
    }
  })
}

const finishTask = (isCheck: boolean, noteInfo: NotesResItem) => {
  noteInfo.taskStatus = isCheck ? 1 : 0
  editNotes(noteInfo).then(() => {
    getNoteList()
    getTaskLoadNum()
  })
}

const tabChange = () => {
  getNoteList()
}
</script>
<style scoped lang="less">
.nav-btn-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  border: 1px solid #b0b6c1;
  border-radius: 8px;
  width: 60px;
  height: 50px;
  padding: 0px;
  margin-right: 12px;
  cursor: pointer;

  &:hover {
    background-color: rgb(246, 251, 255);
  }
}

.nav-btn {
  border-color: rgb(var(--gray-2));
  color: rgb(var(--gray-8));
  font-size: 24px;
}

li {
  display: flex;
  align-items: center;
}

.note-item {
  border: 1px solid #aaabb0;
  background-color: #f1f4f7;
  display: flex;
  justify-content: space-between;
  align-items: stretch;
  padding: 4px;
  margin: 8px;
  border-radius: 4px;
  color: black;
  max-width: 350px;
  min-width: 250px;

  .note-content {
    flex: 1;
    margin: 0px 6px;
    word-wrap: break-word; /* 或者下面这个新语法 */
    overflow-wrap: break-word;
    word-break: break-all;
  }
}

.red {
  color: #e24f48;
}

.yellow {
  color: #ef8432;
}

.gray {
  color: #88909b;
}
</style>
